package folder

import (
	"context"
	acl2 "gitlab.local/TerraMaster/tos-modules/core/acl"
	folder2 "gitlab.local/TerraMaster/tos-modules/folder"

	//"gitlab.local/DO-module/new-filemanage-module/src/core/fileoperate"
	"gitlab.local/TerraMaster/tos-modules/fileoperate"
	"io"
	"mime/multipart"
	"os"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"gitlab.local/TerraMaster/tos-modules/database"
	"gitlab.local/golibrary/filedownload"
)

var icons = map[string]string{ //快捷方式图标列表
	"folder": "/static/images/desktop/folder.svg",
	"file":   "/static/images/file_manager/file.svg",
	"txt":    "/static/images/file_manager/txt.svg",
	"zip":    "/static/images/file_manager/zip_rar.svg",
	"php":    "/static/images/file_manager/php.svg",
	"html":   "/static/images/file_manager/file.svg",
	"ini":    "/static/images/file_manager/file.svg",
	"mp4":    "/static/images/file_manager/mp4.svg",
	"pdf":    "/static/images/file_manager/pdf.svg",
	"mp3":    "/static/images/file_manager/mp3.svg",
	"image":  "/static/images/file_manager/jpg.svg",
}

type FilesUpload struct {
	UserName string `json:"user_name"` //用户名
	Total    int64  `json:"total"`     //总数
	Index    int64  `json:"index"`     //当前索引
	Data     []byte `json:"data"`      //数据流
	FName    string `json:"f_name"`    //文件名
	SaveDir  string `json:"save_dir"`  //保存目录
}

type FileSystem string

const (
	SMB    FileSystem = "cifs"
	NFS    FileSystem = "nfs"
	DAV    FileSystem = "davfs"
	RCLONE FileSystem = "rclone"
)

type Remoter struct {
	ID              string     `json:"id"`
	SourcePath      string     `json:"source_path"`
	DestinationPath string     `json:"destination_path"`
	Protocol        string     `json:"transport_protocol"`
	TaskName        string     `json:"task_name"`
	Version         string     `json:"version,omitempty"`
	Username        string     `json:"username,omitempty"`
	Password        string     `json:"password,omitempty"`
	OnBoot          int        `json:"power_boot"`
	FileSystem      FileSystem `json:"fs"`
	// 记录创建时间，仅仅是后端用到此字段，因为gin框架返回结果里面的列表总是无序的，需要后端自行排序
	CreateTime string `json:"create_time"` // 例： 202205241842，方便string直接对比值
	RemoteAttr
}

type RemoteAttr struct {
	Total  uint64 `json:"total"`  //unit:GB
	Used   uint64 `json:"used"`   //unit:GB
	Status bool   `json:"status"` //挂载状态
}

type HttpFile interface {
	Filename() string
	Open() (io.ReadCloser, error)
}

type FoldersService interface {
	CheckNFSSMBFolder(string, string, string, string) error
	//UnZipCompress(string, string, string) (int64, error)
	//DeleteDesktopFile(string, string) error
	//CreateDesktopFolder([]string, string, int8) error
	//GetUserShortcutDir(string) (string, error)
	//CreateOexeFile(string, int8, ...string) error
	VerifyQuota(int64, string, string) error
	FileUpload(file folder2.HttpFile, dir string, totalIndex uint64, index uint64, autoDelete bool, size int64, uname string, lastModTime int64) (string, error)
	FileUploadConvention(folder2.HttpFile, string, uint64, uint64, bool, int64, string, int64) (string, error)
	FileUploadXfs(folder2.HttpFile, string, uint64, uint64, string, int64) (string, error)
	UpdateFile(string, *multipart.FileHeader) (int64, error)
	//RemoteDownload(string, string, string) error
	MultimediaPlay(string, string, *gin.Context) error
	RunAllRemoteDownloadTask(string) error
	RunRemoteDownloadTask(string, string) error
	PauseRemoteDownloadTask(string, string) error
	PauseAllRemoteDownloadTask(string) error
	//GetRemoteDownloadList(string) ([]DownloadLog, error)
	BreakRemoteDownloadAll(string) error
	BreakRemoteDownload(string, string) error
	ClearCompleteLogs(string) error
	//SearchFiles(string, string, string, string, string, string, bool, int64, int64, string, bool, share.OrderRule, bool) ([]share.FoldersInfo, error)
	//SearchFiles(filetools.FileTools, bool) ([]share.FoldersInfo, error)
	//Sort([]folder2.SearchFileInfo, share.OrderRule, bool) []folder2.SearchFileInfo
	GetPathSize(string) (uint64, error)
	GetThumbnail(string, *gin.Context) error
	GetVideoCover(path string, c *gin.Context) error
	Thumbnail(string, context.Context) (string, error)
	//DelFoldersWhiteList([]string) ([]string, error)
	//IsRecycle(string) (bool, error)
	//GetShareList(string, string) ([]folder2.ShareFolder, error)
	GetHomeListFilter(string) ([]fileoperate.FoldersInfo, error)
	GetUSBListFilter(string) ([]fileoperate.FoldersInfo, error)
	GetHomeList(string, string) ([]fileoperate.FoldersInfo, error)
	IsRootAdmin(string) (bool, error)
	IsAdmin(string) (bool, error)
	GetFoldersFilter(string, string, int, int, fileoperate.OrderRule, bool, int, context.Context) (*fileoperate.Folders, error)
	EditFile(string, string) error
	GetDirTree(string, string, context.Context) ([]fileoperate.FoldersInfo, error)
}

type FileTimer struct {
	stop chan struct{}
	t    *time.Timer
}

type ShareFolder struct {
	Name  string `json:"name"`   // name
	Path  string `json:"path"`   // path
	IsDir bool   `json:"is_dir"` // true:文件夹 false:文件
}

type download struct {
	sync.Mutex
	queue []*filedownload.Download
}

type Folder struct {
	db             database.DbGetter
	fOptGetter     fileoperate.Getter
	Acl            acl2.FolderAttrService
	delTimer       map[string]*FileTimer
	delRWMutex     sync.RWMutex
	xfsUpdate      map[string]*os.File //xfs文件上传句柄
	updateMap      map[string]*os.File //文件上传句柄集合
	thumbnailMutex sync.Mutex

	remoteDownloadQueue map[string]*download //远程下载队列[用户名称][下载队列]
	remoteLimitNum      uint8                //远程下载最大任务数限制
	remoteRunNum        uint8                //正在运行任务数
}

type Acl struct {
	Name string `json:"name"` //名称
	R    bool   `json:"r"`    //读权限
	W    bool   `json:"w"`    //写权限
	X    bool   `json:"x"`    //执行权限
}

type FileSortData struct {
	Files []string
	Dirs  []string
}

type RecentlyTime struct {
	Path string
	Time time.Time
}

// NewFolder 实例化
func NewFolder(dbGetter database.DbGetter,
	fOptGetter fileoperate.Getter,
	acl acl2.FolderAttrService) *Folder {
	return &Folder{
		db:         dbGetter,
		fOptGetter: fOptGetter,
		Acl:        acl,

		delTimer:  make(map[string]*FileTimer),
		updateMap: make(map[string]*os.File),

		remoteLimitNum:      5, //限制并行任务为5个
		remoteDownloadQueue: make(map[string]*download),
	}
}
